package main

import (
	"embed"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/pelletier/go-toml"
	"io"
	"io/fs"
	"log"
	"net/http"
	"os"
	config2 "passwordBook/config"
	"passwordBook/entity"
	_ "passwordBook/routers"
	"passwordBook/sql"
	"time"
)

var frontendFS embed.FS
var commonConfig = config2.CommonConfig{}
var configFilePath, _ = beego.AppConfig.String("commonConfigFilePath")
var GlobalDb = sql.Database{}

func readToml() {
	tomlTree, loadErr := toml.LoadFile(configFilePath)
	if loadErr != nil {
		panic("加载配置文件出错，错误原因：" + loadErr.Error())
	} else {
		config := config2.CommonConfig{}
		umerr := tomlTree.Unmarshal(&config)
		if umerr != nil {
			panic("读取配置文件出错，错误原因：" + umerr.Error())
		} else {
			commonConfig = config
		}
	}

}
func writeToml() {

	data, merr := toml.Marshal(&commonConfig)

	if merr != nil {
		panic("序列化配置文件出错，错误原因：" + merr.Error())
	} else {
		err := os.WriteFile(configFilePath, data, 0777)
		if err != nil {
			fmt.Println("错误：" + err.Error())
			panic("打开配置文件失败，失败原因：" + err.Error())
		}
	}
}

func mainInit() {
	_, ferr := os.Open(configFilePath)
	exist := ferr == nil
	if !exist {
		os.Mkdir("setting", 0777)
		os.Create(configFilePath)
		commonConfig.MainVersion = 1
		commonConfig.SubVersion = 0
		commonConfig.DebugVersion = 0
		commonConfig.DataStoreMethod = "local"
		commonConfig.DataBaseFilePath = "pwds.db"
		commonConfig.IsFirstStart = true
		time.Sleep(1 * 1000)
		writeToml()
	}
	readToml()
	if (commonConfig == config2.CommonConfig{}) {
		commonConfig.MainVersion = 1
		commonConfig.SubVersion = 0
		commonConfig.DebugVersion = 0
		commonConfig.DataStoreMethod = "local"
		commonConfig.DataBaseFilePath = "pwds.db"
		commonConfig.IsFirstStart = true
		writeToml()
		readToml()
	}

}
func CreateLogger() {
	os.Mkdir("./log", 0777)
	file, err := os.Create(fmt.Sprintf("./log/log-%s.log", time.Now().Format("2006-01-02 15_04_05")))

	if err != nil {
		fmt.Println("无法打开文件", err.Error())

	} else {
		log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
		writers := io.MultiWriter(os.Stdout, file)
		log.SetOutput(writers)

	}
}
func main() {
	mainInit()
	CreateLogger()
	beego.BConfig.Listen.EnableAdmin = true
	beego.BConfig.Listen.AdminAddr = "localhost"
	beego.BConfig.Listen.AdminPort = 8088
	if commonConfig.DataStoreMethod == "local" {
		filePath := commonConfig.DataBaseFilePath
		sql.GLOBAL_DB = GlobalDb.CreateDbConnection(filePath, "", "", "", "local")

	} else {
		url := commonConfig.DataBaseUrl
		name := commonConfig.DataBaseName
		username := commonConfig.DataBaseUsername
		password := commonConfig.DataBasePassword
		sql.GLOBAL_DB = GlobalDb.CreateDbConnection(url, username, password, name, "mysql")
	}
	sql.GLOBAL_DB.Db.AutoMigrate(&entity.PwBook{})
	sql.GLOBAL_DB.Db.AutoMigrate(&entity.PwItem{})
	// 获取嵌入的子文件系统
	subFS, _ := fs.Sub(frontendFS, "static/")

	// 设置静态文件路由
	beego.SetStaticPath("/", "static/") // 可选：开发时使用磁盘文件

	// 托管前端静态资源（生产用嵌入文件）
	beego.Handler("/static/*", http.StripPrefix("/static/",
		http.FileServer(http.FS(subFS))),
	)
	//// 处理 SPA 前端路由：所有未匹配路由返回 index.html
	//beego.InsertFilter("*", beego.BeforeExec, func(ctx *context.Context) {
	//	if !strings.HasPrefix(ctx.Request.URL.Path, "/") && // 排除 API 路由
	//		!strings.HasPrefix(ctx.Request.URL.Path, "/static") {
	//		ctx.Request.URL.Path = "/index.html"
	//	}
	//})

	beego.Run()
}
